package com.cloudwise.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudwise.entity.Result;
import com.cloudwise.entity.ReturnBean;
import com.cloudwise.entity.ReturnResult;
import com.cloudwise.entity.Tester;
import com.cloudwise.service.ResultService;
import com.cloudwise.service.TesterService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.*;

/**
 * (Result)表控制层
 *
 * @author makejava
 * @since 2021-11-26 17:38:36
 */
@RestController
@RequestMapping("/result")
public class ResultController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private ResultService resultService;
    @Resource
    private TesterService testerService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param result 查询实体
     * @return 所有数据
     */
    @GetMapping("selectAll")
    public ReturnBean selectAll(Long page, Long limit, Result result) {
        limit = limit * 30;
        Page<Result> pageObj = new Page<>(page, limit);
        Page<Result> resultPage = this.resultService.page(pageObj, new QueryWrapper<>(result));
        List<Result> resultList = resultPage.getRecords();
        Map<Integer, ReturnResult> rrMap = new LinkedHashMap<>();
        ReturnResult rr;
        for(Result res : resultList){
            rr = rrMap.get(res.getTesterId());
            if (rr == null){
                rr = new ReturnResult(this.testerService.getById(res.getTesterId()),0, 0, 0, 0,0,0,0,0);
                rrMap.put(res.getTesterId(), rr);
            }
            if((rr.getANum1()+rr.getBNum1()+rr.getCNum1()+rr.getDNum1()) < 15){
                if (res.getResult().equals("A")){
                    rr.setANum1(rr.getANum1() + 1);
                }else if(res.getResult().equals("B")){
                    rr.setBNum1(rr.getBNum1() + 1);
                }else if(res.getResult().equals("C")){
                    rr.setCNum1(rr.getCNum1() + 1);
                }else {
                    rr.setDNum1(rr.getDNum1() + 1);
                }
            }else{
                if (res.getResult().equals("A")){
                    rr.setANum2(rr.getANum2() + 1);
                }else if(res.getResult().equals("B")){
                    rr.setBNum2(rr.getBNum2() + 1);
                }else if(res.getResult().equals("C")){
                    rr.setCNum2(rr.getCNum2() + 1);
                }else {
                    rr.setDNum2(rr.getDNum2() + 1);
                }
            }
        }
        List<ReturnResult> lrr = mapToList(rrMap);
        return super.success(lrr, (long) (resultList.size()/30));
    }

    private List<ReturnResult> mapToList(Map<Integer, ReturnResult> map){
        List<ReturnResult> rr = new ArrayList<>();
        ReturnResult r;
        for (Integer i : map.keySet()){
            r = map.get(i);
            r.computeCharacter();
            rr.add(r);
        }
        return rr;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param testerId 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public ReturnBean selectOne(@PathVariable("id") Integer testerId) {
        List<Result> resultList = this.resultService.findResultByTesterId(testerId);
        if (resultList == null || resultList.size() == 0){
            return super.fail(null);
        }
        ReturnResult rr = formatReturnResult(resultList, testerId);
        rr.computeCharacter();
        return super.success(rr);
    }

    @GetMapping("/selectResult")
    public ReturnBean selectResult(HttpSession session){
        Tester tester = (Tester) session.getAttribute("tester");
        return selectOne(tester.getTesterId());
    }

    private ReturnResult formatReturnResult(List<Result> resultList, Integer testerId){
        Result result = resultList.get(0);
        ReturnResult rr = new ReturnResult(this.testerService.getById(testerId),
                0, 0, 0, 0,0,0,0,0);
        int size = resultList.size();
        Result res;
        for(int i=0;i<size/2;i++){
            res = resultList.get(i);
            if (res.getResult().equals("A")){
                rr.setANum1(rr.getANum1() + 1);
            }else if(res.getResult().equals("B")){
                rr.setBNum1(rr.getBNum1() + 1);
            }else if(res.getResult().equals("C")){
                rr.setCNum1(rr.getCNum1() + 1);
            }else {
                rr.setDNum1(rr.getDNum1() + 1);
            }
        }
        for(int i=size/2;i<size;i++){
            res = resultList.get(i);
            if (res.getResult().equals("A")){
                rr.setANum2(rr.getANum2() + 1);
            }else if(res.getResult().equals("B")){
                rr.setBNum2(rr.getBNum2() + 1);
            }else if(res.getResult().equals("C")){
                rr.setCNum2(rr.getCNum2() + 1);
            }else {
                rr.setDNum2(rr.getDNum2() + 1);
            }
        }
        return rr;
    }

    /**
     * 新增数据
     *
     * @param result 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    public ReturnBean insert(@RequestBody Result result) {
        boolean save = this.resultService.save(result);
        if (save){
            return super.success(result);
        }else {
            return super.fail(result);
        }
    }

    /**
     * 修改数据
     *
     * @param result 实体对象
     * @return 修改结果
     */
    @PutMapping("/update")
    public ReturnBean update(@RequestBody Result result) {
        boolean update = this.resultService.updateById(result);
        if (update){
            return super.success(update);
        }else {
            return super.fail(result);
        }
    }

    @PostMapping("/score")
    public ReturnBean score(@RequestBody Map<Integer, String> answer, HttpSession session){
        Tester tester = (Tester) session.getAttribute("tester");
        if(answer.size() < 30 || tester == null){
            return super.fail(null);
        }
        List<Result> resultList = new ArrayList<>();
        for(Integer questionId : answer.keySet()){
            resultList.add(new Result(tester.getTesterId(), questionId, answer.get(questionId)));
        }
        this.resultService.saveBatch(resultList);
        tester.setTestTime(new Date());
        this.testerService.updateById(tester);
        ReturnResult rr = formatReturnResult(resultList, tester.getTesterId());
        rr.computeCharacter();
        return super.success(rr);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ReturnBean delete(@RequestParam("id") List<Long> idList) {
        for (Long id : idList){
//            Tester tester = this.testerService.getById(id);
//            tester.setTestTime(null);
//            this.testerService.updateById(tester);
            this.testerService.update(new UpdateWrapper<Tester>().eq("tester_id", id).set("test_time", null));
        }
        return super.success(this.resultService.removeByTesterIds(idList));
    }
}

